package com.ye.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ye.reggie.common.CustomException;
import com.ye.reggie.dto.SetmealDto;
import com.ye.reggie.mapper.SetmealMapper;
import com.ye.reggie.pojo.Dish;
import com.ye.reggie.pojo.Setmeal;
import com.ye.reggie.pojo.SetmealDish;
import com.ye.reggie.service.SetmealDishService;
import com.ye.reggie.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper,Setmeal> implements SetmealService {

    @Autowired
    private SetmealDishService setmealDishService;

    /**
     *  新增套餐，同时需要保存套餐和菜品的关联关系
     *
     * @author 叶旭晖
     * @date 2022/4/26 14:59
     * @param [setmealDto]
     * @return void
     */
    @Override
    @Transactional
    public void saveWithDish(SetmealDto setmealDto) {
        //保存套餐的基本信息，操作setmeal，执行insert
        this.save(setmealDto);

        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        setmealDishes.stream().map((item->{
            item.setSetmealId(setmealDto.getId());
            return item;
        })).collect(Collectors.toList());


        //保存套餐和菜品的关联关系setmeal_dish，操作insert
        setmealDishService.saveBatch(setmealDishes);

    }

    /**
     *  删除套餐，同时需要删除套餐和菜品的关联数据
     *
     * @author 叶旭晖
     * @date 2022/4/26 15:35
     * @param [ids]
     * @return void
     */
    @Override
    @Transactional
    public void deleteWithDish(List<Long> ids) {
        //查询套餐状态，确定是否可以删除
        LambdaQueryWrapper<Setmeal> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.in(Setmeal::getId,ids);
        lambdaQueryWrapper.eq(Setmeal::getStatus,1);
        //如果不能删除，抛出一个业务异常
        long count = this.count(lambdaQueryWrapper);
        if(count > 0){
            throw new CustomException("套餐正在售卖中，不能删除");
        }

        //如果可以删除，先删除套餐表中的数据
        this.removeByIds(ids);

        //删除关系表中的数据
        LambdaQueryWrapper<SetmealDish> lambdaQueryWrapper1 = new LambdaQueryWrapper<>();
        lambdaQueryWrapper1.in(SetmealDish::getSetmealId,ids);

        setmealDishService.remove(lambdaQueryWrapper1);

    }
}
